package com.jfs.strategy.message.impl;

import com.jfs.enums.MessageEnum;
import com.jfs.envent.EventPublisher;
import com.jfs.envent.entity.MessageDeviceInfoEntity;
import com.jfs.observer.request.abstracts.AbstractProcessor;
import com.jfs.strategy.message.MessageStrategy;
import com.jfs.utils.XstreamUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.sip.InvalidArgumentException;
import javax.sip.RequestEvent;
import javax.sip.SipException;
import java.text.ParseException;

/**
 * @Description 设备详情消息策略处理类
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022/7/25
 */
@Component
@Slf4j
@AllArgsConstructor
public class MessageDeviceInfoStrategy implements MessageStrategy {
    private final EventPublisher eventPublisher;

    @Override
    public boolean support(String content) {
        return content.contains(MessageEnum.MESSAGE_DEVICE_INFO.getCmd());
    }

    @Override
    public void processor(String content, AbstractProcessor abstractProcessor, RequestEvent requestEvent) {
        try {
            MessageDeviceInfoEntity messageDeviceInfoEntity = XstreamUtil.toBean(MessageDeviceInfoEntity.class, content);
            messageDeviceInfoEntity.setRequestEvent(requestEvent);
            messageDeviceInfoEntity.setIp(abstractProcessor.getIpByRequest(requestEvent));
            messageDeviceInfoEntity.setPort(abstractProcessor.getPortFromRequest(requestEvent));
            messageDeviceInfoEntity.setTransport(abstractProcessor.getTransactionFormRequest(requestEvent));
            //发布查询到设备详情事件
            eventPublisher.publish(messageDeviceInfoEntity);
            //回复成功
            abstractProcessor.doSuccess(requestEvent);
        } catch (SipException | ParseException | InvalidArgumentException e) {
            log.info("处理查询设备详情发生异常:{}", e.getMessage());
            e.printStackTrace();
        }
    }
}
